package com.star.mall.persistence.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.star.mall.constants.KeyConstant;
import com.star.mall.persistence.entity.RoleAuth;
import com.star.mall.persistence.mapper.RoleAuthMapper;
import com.star.mall.persistence.service.IRoleAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限表  服务实现类
 * </p>
 *
 * @author StarQ
 * @since 2021-05-02
 */
@Service
public class RoleAuthServiceImpl extends ServiceImpl<RoleAuthMapper, RoleAuth> implements IRoleAuthService {

    @Override
    public Set<String> getAuthKeyByRoleIds(Set<String> roleIds) {
        QueryWrapper<RoleAuth> wrapper = new QueryWrapper<>();
        wrapper.in("role_id_", roleIds);
        wrapper.eq("type_", RoleAuth.MENU);
        return list(wrapper).stream().map(RoleAuth::getAuthKey).collect(Collectors.toSet());
    }

    @Override
    @CacheEvict(value = KeyConstant.MENU_CACHE_NAME, allEntries = true)
    public void saveRoleAuth(List<String> authKeys, String roleId, Integer type) {
        QueryWrapper<RoleAuth> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id_", roleId);
        wrapper.eq("type_", type);
        Set<String> existAuthKeys = list(wrapper).stream().map(RoleAuth::getAuthKey).collect(Collectors.toSet());

        authKeys.forEach(authKey -> {
            if (!existAuthKeys.contains(authKey)) {
                RoleAuth roleAuth = new RoleAuth();
                roleAuth.setAuthKey(authKey);
                roleAuth.setRoleId(roleId);
                roleAuth.setType(type);
                save(roleAuth);
            }else {
                existAuthKeys.remove(authKey);
            }
        });

        if (!existAuthKeys.isEmpty()) {
            UpdateWrapper<RoleAuth> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("auth_key_", existAuthKeys);
            updateWrapper.eq("role_id_", roleId);
            updateWrapper.eq("type_", type);
            remove(updateWrapper);
        }
    }
}
